<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable, HasRoles;

    # 需要添加
    protected $guard_name = 'api';
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'nickname', 'password', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [

    ];

    protected static function boot()
    {
        parent::boot();
          // 监听 User 的创建事件，用于初始化 password 和 level 字段值
        static::creating(function (User $user) {
            // 如果创建的是一个根类目
            if (is_null($user->parent_id)) {
                // 将层级设为 1 顶层层级为1
                $user->level = 0;

                $user->path  = '-';

            } else {
                // 将层级设为父类目的层级 + 1
                $user->level = $user->parent->level + 1;

                $user->path  = $user->parent->path.$user->parent_id.'-';

            }

            # 密码加密设置
            $user->password = Bcrypt($user->password);

            # 设置ip地址
            if (is_null($user->login_ip)) {
                $user->ip = request()->getClientIp();
            }

            if (is_null($user->old_login_ip)) {
                $user->old_ip = request()->getClientIp();
            }
        });
    }

    public function parent()
    {
        return $this->belongsTo(get_class($this),'parent_id','id');
    }

    public function children()
    {
        return $this->hasMany(get_class($this), 'parent_id');
    }
}
